package com.example.home.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import com.example.home.R;
import com.example.home.adapter.BannerAdapter;
import com.example.home.adapter.NewsAdapter;
import com.example.home.adapter.NewsHotApter;
import com.example.home.adapter.ServletAdapter;
import com.example.home.bean.BanBen;
import com.example.home.bean.HotBean;
import com.example.home.bean.NewsListBean;
import com.example.home.bean.ServiceBean;
import com.google.android.material.tabs.TabLayout;
import com.google.gson.Gson;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import static android.content.ContentValues.TAG;

public class HomeFragment extends Fragment {

    private OkHttpClient okHttpClient;
    private Handler handler;
    private Request request;
    private ArrayList<View> reyuan_list;
    private List<BanBen.RowsBean> beans;
    private List<ServiceBean.RowsBean> rowsDTOS_list;
    private HotBean hotBean;
    private RecyclerView re_servlet;
    private View dot1;
    private View dot2;
    private View dot3;
    private HotBean re_news ;
    private ViewPager viewPager;
    private View view;
    private Gson gson;
    private TabLayout tab_new;
    private NewsListBean newsListBean;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_home, container, false);
        viewPager = view.findViewById(R.id.bannervp);
        re_servlet = view.findViewById(R.id.re_servlet);
        tab_new = view.findViewById(R.id.tab_new);

        initview();
        //轮播图
        getBannerData();
        //新闻列表
        getNewDate(13);
        NewsList();
        //热门主题
        getHotDate();
        //全部服务
        getservice();

        //指示点
        getYuan();

        return view;
    }

    private void NewsList() {
        request = new Request.Builder()
                .url("http://124.93.196.45:10001/prod-api/api/park/press/category/list")
                .build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                Log.e(TAG,"网络访问失败");
                e.printStackTrace();
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                 String json = response.body().string();
                gson = new Gson();
                newsListBean = gson.fromJson(json, NewsListBean.class);
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        for (NewsListBean.DataBean dataBean : newsListBean.getData()){
                            TabLayout.Tab tab = tab_new.newTab();
                            tab.setText(dataBean.getName());
                            tab_new.addTab(tab);
                        }
                        Getnewslist();
                    }
                });
            }
        });
    }

    private void Getnewslist() {
        tab_new.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                int position = tab.getPosition();
                String tabtext = tab.getText().toString();
                if (newsListBean.getData().get(position).getName().equals(tabtext)){
                    getNewDate(newsListBean.getData().get(position).getId());
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }

    private void getservice() {
        request =  new Request.Builder()
/*                .addHeader("token", Contants.TOKEN)*/
                .url("http://124.93.196.45:10001/prod-api/api/service/list")
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                e.printStackTrace();
                Log.d("xx","bb");
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                String json =  response.body().string();
                Log.d("xjson",json);
                gson = new Gson();
                ServiceBean banner = gson.fromJson(json, ServiceBean.class);
                rowsDTOS_list = banner.getRows();
                handler.post(new Runnable() {
                    @Override
                    public void run(){
                        binServer();
                    }
                });
            }
        });
    }

    private void binServer() {
            ServletAdapter serverApter = new ServletAdapter(this.getActivity(),rowsDTOS_list);
            GridLayoutManager gridLayoutManager = new GridLayoutManager(getContext(),5);
            re_servlet.setLayoutManager(gridLayoutManager);
            re_servlet.setAdapter(serverApter);

    }

    private void getHotDate() {
        request = new Request.Builder().url("http://124.93.196.45:10001/prod-api/press/press/list?hot=Y").build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                Log.e(TAG,"网络访问成功");
                String json = response.body().string();
                Gson gson = new Gson();
                hotBean = gson.fromJson(json, HotBean.class);
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        binHot();
                    }
                });
            }
        });
    }

    private void binHot() {
        RecyclerView recyclerView = view.findViewById(R.id.rcv_hot);
        NewsHotApter newsHotApter = new NewsHotApter(getContext(),hotBean.getRows());
        GridLayoutManager gridLayoutManager = new GridLayoutManager(getContext(),2);
        recyclerView.setLayoutManager(gridLayoutManager);
        recyclerView.setAdapter(newsHotApter);
    }

    private void getNewDate(int id) {
        request = new Request.Builder().url("http://124.93.196.45:10001/prod-api/api/park/press/press/list?type="+id).build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                e.printStackTrace();
            }
            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {

                String json = response.body().string();
                System.out.println("json"+json);
                Gson gson = new Gson();
                re_news = gson.fromJson(json, HotBean.class);
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        binnewdate();
                    }
                });
            }
        });
    }
    private void binnewdate() {
        RecyclerView recyclerView =view.findViewById(R.id.rcy_new);
        NewsAdapter newsApter = new NewsAdapter(getContext(),re_news.getRows());
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
        recyclerView.setLayoutManager(linearLayoutManager);
        recyclerView.setAdapter(newsApter);
    }

    private void getYuan() {
        reyuan_list = new ArrayList<>();
        dot1 = view.findViewById(R.id.dot1);
        dot2 = view.findViewById(R.id.dot2);
        dot3 = view.findViewById(R.id.dot3);
        reyuan_list.add(dot1);
        reyuan_list.add(dot2);
        reyuan_list.add(dot3);
    }

    private void initview() {
        okHttpClient = new OkHttpClient();
        handler = new Handler();
    }

    private void getBannerData() {
        request =  new Request.Builder()
                .url("http://124.93.196.45:10001/prod-api/api/rotation/list")
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                Log.e("TAG","网络访问失败");
                e.printStackTrace();
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                String json =  response.body().string();
                Log.e("TAG","网络访问成功");
                Log.d("xjson",json);
                Gson gson = new Gson();
                BanBen banner = gson.fromJson(json, BanBen.class);
                beans = banner.getRows();
                handler.post(new Runnable() {
                    @Override
                    public void run(){
                        bindBannerData();
                    }
                });
            }
        });
    }

    private void bindBannerData() {
        BannerAdapter bannerAdapter = new BannerAdapter(beans, HomeFragment.this.getContext());
        viewPager.setAdapter(bannerAdapter);
        mHandler.sendEmptyMessageDelayed(0, 3 * 1000);

        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                for (int i = 0; i < beans.size(); i++) {
                    reyuan_list.get(i).setBackground(view.getContext().getDrawable(R.drawable.yuan_h));
                }
                reyuan_list.get(position).setBackground(view.getContext().getDrawable(R.drawable.yuan_w));
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);

            if (msg.what == 0) {
                int index = viewPager.getCurrentItem();
                index = (index + 1) % beans.size();
                viewPager.setCurrentItem(index);
                mHandler.sendEmptyMessageDelayed(0, 3 * 1000);
            }
        }
    };


}